package net.googlecode.garzha.controllers;

import net.googlecode.garzha.domains.Person;
import net.googlecode.garzha.services.PersonService;
import net.googlecode.garzha.services.SecurityService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
/**
 * Controller of register page.
 */
public class RegisterController {

    @Autowired
    private PersonService personService;
    @Autowired
    private SecurityService securityService;

    protected static final Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/register")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ModelAndView mv = new ModelAndView("register");
        mv.addObject("root", request.getContextPath());
         mv.addObject("group",personService.getListGroup() );
        logger.info("REGISTER Returning user page view");
        return mv;
    }

    /**
     * Controller add new person into database and sets the default settings.
     * @param person
     * @param result
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("person") Person person,
                             BindingResult result) {
        logger.info("REGISTER add function ");

        person.setAuthority("ROLE_USER");
        person.setRate(50);
        person.setEnabled(true);
        person.setImgurl("no.jpg");
        person.setEmail(person.getEmail().toLowerCase());
        personService.addPerson(person);
        logger.info("REGISTER return function ");
        return "redirect:/index";
    }


}